package jgl.vajra.management.widget.utils;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.res.Resources;
import android.os.Build;
import android.os.SystemClock;
import android.text.InputType;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import jgl.vajra.management.R;
import jgl.vajra.management.constant.AppConfig;
import jgl.vajra.management.widget.base.BaseApplication;
import jgl.vajra.management.widget.interfaces.TimeCountdownListener;
import jgl.vajra.management.widget.retrofithelper.interceptor.NetworkInterceptor;
import jgl.vajra.management.widget.retrofithelper.rxsubscriber.CommonObserver;
import jgl.vajra.management.widget.view.tablayout.TabLayout;
import com.orhanobut.logger.Logger;

import org.jetbrains.annotations.Nullable;
import org.json.JSONObject;

import java.io.EOFException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Connection;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

import static android.content.Context.CLIPBOARD_SERVICE;

/**
 * @Author zhangshuqi
 * @CreateTime 2018/3/19
 * @Describe
 */

public class CommonUtils {


    /*
     * 适配nestedScrollView 嵌套混乱 滑动不流畅
     * */
    public static void setManagerConfig(RecyclerView.LayoutManager manager, RecyclerView recyclerView) {
        if (manager instanceof LinearLayoutManager) {
            LinearLayoutManager linearLayoutManager = (LinearLayoutManager) manager;
            linearLayoutManager.setSmoothScrollbarEnabled(true);
        } else if (manager instanceof GridLayoutManager) {
            GridLayoutManager linearLayoutManager = (GridLayoutManager) manager;
            linearLayoutManager.setSmoothScrollbarEnabled(true);
        }
        manager.setAutoMeasureEnabled(true);
        recyclerView.setHasFixedSize(true);
        recyclerView.setNestedScrollingEnabled(false);
    }

    public static boolean isAppDebug() {
        return getAppStatusModel() == AppConfig.TYPE_DEBUG;
    }

    public static boolean isAppRelease() {
        return getAppStatusModel() == AppConfig.TYPE_RELEASE;
    }

    public static boolean isAppDebugAndTestRelease() {
        return getAppStatusModel() != AppConfig.TYPE_RELEASE;
    }

    public static int getAppStatusModel() {
        return BaseApplication.getAppStatusModel();
    }


    public static void clearListOfIndex(List data, int index) {
        for (int i = data.size() - 1; i >= index; i--) {
            data.remove(i);
        }
    }

    public static void setIndicator(final TabLayout tabs, final int leftDip, final int rightDip) {
        tabs.post(new Runnable() {
            @Override
            public void run() {
                Class<?> tabLayout = tabs.getClass();
                Field tabStrip = null;
                try {
                    tabStrip = tabLayout.getDeclaredField("mTabStrip");
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }

                tabStrip.setAccessible(true);
                LinearLayout llTab = null;
                try {
                    llTab = (LinearLayout) tabStrip.get(tabs);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }

                int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics());
                int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());


                for (int i = 0; i < llTab.getChildCount(); i++) {
                    View child = llTab.getChildAt(i);
                    child.setPadding(0, 0, 0, 0);
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
                    params.leftMargin = left;
                    params.rightMargin = right;
                    child.setLayoutParams(params);
                    child.invalidate();
                }
            }

        });


    }

    public static void printNetLog(Interceptor.Chain chain, Request request, Response response, StringBuffer bfLog, NetworkInterceptor.Level level) throws IOException {
   /*     if (response.status() == 200) {
            //这里是网络拦截器，可以做错误处理
            MediaType mediaType = response.body().contentType();
            //当调用此方法java.lang.IllegalStateException: closed，原因为OkHttp请求回调中response.body().string()只能有效调用一次
            byte[] data = response.body().bytes();
            byte[] bytes = Base64.decode(data, Base64.DEFAULT);
            data = GZIPUtils.uncompress(bytes);
            *//*if (GZIPUtils.isGzip(response.headers())) {
                //请求头显示有gzip，需要解压

            }*//*
            //创建一个新的responseBody，返回进行处理
            response = response.newBuilder()
                    .body(ResponseBody.create(mediaType, data))
                    .build();
        }*/

        //   bfLog.append("操作时间：" + TimeUtils.getSystemDateToSecond() + "\n");
        if (level == NetworkInterceptor.Level.NONE) {
            return;
        }

        boolean logBody = level == NetworkInterceptor.Level.BODY;
        boolean logHeaders = logBody || level == NetworkInterceptor.Level.HEADERS;

        RequestBody requestBody = request.body();
        boolean hasRequestBody = requestBody != null;

        Connection connection = chain.connection();
        Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1;
        String requestStartMessage = "-->\n请求类型 " + request.method() + "\n接口地址：" + request.url() + "\n请求协议：" + protocol;
        if (!logHeaders && hasRequestBody) {
            requestStartMessage += " (" + requestBody.contentLength() + "-byte body)\n";
        }
        bfLog.append(requestStartMessage + "\n");

        //
        // bfLog.append(requestStartMessage);

        if (logHeaders) {
            if (hasRequestBody) {
                // Request body headers are only present when installed as a network interceptor. Force
                // them to be included (when available) so there values are known.
                if (requestBody.contentType() != null) {
                    bfLog.append("Content-Type: " + requestBody.contentType() + "\n");
                }
                if (requestBody.contentLength() != -1) {
                    bfLog.append("Content-Length: " + requestBody.contentLength() + "\n");
                }
            }

            Headers headers = request.headers();
            for (int i = 0, count = headers.size(); i < count; i++) {
                String name = headers.name(i);
                // Skip headers from the request body as they are explicitly logged above.
                if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
//                    bfLog.append(title + ": " + headers.value(i));
                    bfLog.append(name + ": " + headers.value(i));
                }
            }

            if (!logBody || !hasRequestBody) {
                bfLog.append("--> END " + request.method() + "\n");
            } else if (bodyEncoded(request.headers())) {
                bfLog.append("--> END " + request.method() + " (encoded body omitted)" + "\n");
            } else {
                Buffer buffer = new Buffer();
                requestBody.writeTo(buffer);
                Charset charset = NetworkInterceptor.UTF8;
                MediaType contentType = requestBody.contentType();
                if (contentType != null) {
                    charset = contentType.charset(NetworkInterceptor.UTF8);
                }

                if (isPlaintext(buffer)) {
                    bfLog.append("请求参数:+\n" + buffer.readString(charset) + "\n");
                    bfLog.append("--> END " + request.method()
                            + " (" + requestBody.contentLength() + "-byte body)" + "\n");
                } else {
                    bfLog.append("--> END " + request.method() + " (binary "
                            + requestBody.contentLength() + "-byte body omitted)" + "\n");
                }
            }
        }

        long startNs = System.nanoTime();

        long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

        ResponseBody responseBody = response.body();
        long contentLength = responseBody.contentLength();
        String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
        bfLog.append(
                "status" + response.code() + "\n" +
                        "message" + response.message() + "\n" +
                        "request" + response.request().url() + "\n " +
                        "(" + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " body" : "") + ')' + "\n");

        if (logHeaders) {
            Headers headers = response.headers();
            for (int i = 0, count = headers.size(); i < count; i++) {
                bfLog.append(headers.name(i) + ": " + headers.value(i) + "\n");
            }
            if (!logBody) {
                bfLog.append("<-- END HTTP" + "\n");
            } else if (bodyEncoded(response.headers())) {
                bfLog.append("<-- END HTTP (encoded body omitted)" + "\n");
            } else {
                BufferedSource source = responseBody.source();
                source.request(Long.MAX_VALUE); // Buffer the entire body.
                Buffer buffer = source.buffer();
                Charset charset = NetworkInterceptor.UTF8;
                MediaType contentType = responseBody.contentType();
                if (contentType != null) {
                    charset = contentType.charset(NetworkInterceptor.UTF8);
                }

                if (!isPlaintext(buffer)) {
                    bfLog.append("<-- END HTTP (binary " + buffer.size() + "-byte body omitted " + "\n");
                    return;
                }

                if (contentLength != 0) {
                    String readString = buffer.clone().readString(charset);
                    bfLog.append("响应数据：" + "\n");
                    try {

                        bfLog.append((new JSONObject(readString)).toString(4));
                    } catch (Exception _e) {
                        _e.printStackTrace();
                        bfLog.append(readString);
                    }
                }

                bfLog.append("END HTTP (" + buffer.size() + "-bit body)" + "\n");
                bfLog.append("接口访问结束==================================接口访问结束==================================");
            }
        }
    }

    public static boolean isPlaintext(Buffer buffer) {
        try {
            Buffer prefix = new Buffer();
            long byteCount = buffer.size() < 64 ? buffer.size() : 64;
            buffer.copyTo(prefix, 0, byteCount);
            for (int i = 0; i < 16; i++) {
                if (prefix.exhausted()) {
                    break;
                }
                int codePoint = prefix.readUtf8CodePoint();
                if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
                    return false;
                }
            }
            return true;
        } catch (EOFException e) {
            return false; // Truncated UTF-8 sequence.
        }
    }

    public static boolean bodyEncoded(Headers headers) {
        String contentEncoding = headers.get("Content-Encoding");
        return contentEncoding != null && !contentEncoding.equalsIgnoreCase("identity");
    }

    public static List<String> getValueByName(String url) {
        List<String> result = new ArrayList<>();
        int index = url.indexOf("?");
        String temp = url.substring(index + 1);
        String[] keyValue = temp.split("&");
        Collections.addAll(result, keyValue);
        return result;
    }

    private static List<Throwable> retryTokenInvalidList = new ArrayList<>();

    public static List<Throwable> getRetryTokenInvalidList() {
        return retryTokenInvalidList;
    }

    public static void setTabLayoutIndicator(final TabLayout tabs, final int leftDip, final int rightDip, int centerDip) {

        tabs.post(new Runnable() {
            @Override
            public void run() {
                Class<?> tabLayout = tabs.getClass();
                try {
                    Field tabStrip = tabLayout.getDeclaredField("mTabStrip");
                    if (tabStrip == null) return;
                    tabStrip.setAccessible(true);
                    LinearLayout llTab = (LinearLayout) tabStrip.get(tabs);
                    if (llTab == null) return;
                    int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics());
                    int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());


                    for (int i = 0; i < llTab.getChildCount(); i++) {
                        View child = llTab.getChildAt(i);
                        child.setPadding(0, 0, 0, 0);
                        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
                        params.leftMargin = left;
                        params.rightMargin = right;
                        child.setLayoutParams(params);
                        child.invalidate();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }

    public static void seePassword(EditText v) {
        if (v.getInputType() == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
            v.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        } else {
            v.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        }

    }


    public static void setupForWeriteActivities(final WebView wv_content) {
        if (wv_content == null) {
            return;
        }

        //  wv_content.setFocusable(true);
        //  wv_content.setFocusableInTouchMode(true);
        //  wv_content.requestFocusFromTouch();
        WebSettings webSetting = wv_content.getSettings();
        webSetting.setJavaScriptEnabled(true);//允许js调用
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);//支持通过JS打开新窗口
        webSetting.setAllowFileAccess(true);//在File域下，能够执行任意的JavaScript代码，同源策略跨域访问能够对私有目录文件进行访问等
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);//控制页面的布局(使所有列的宽度不超过屏幕宽度)
        webSetting.setSupportZoom(true);//支持页面缩放
        webSetting.setBuiltInZoomControls(false);//进行控制缩放
        webSetting.setAllowContentAccess(true);//是否允许在WebView中访问内容URL（Content Url），默认允许
        webSetting.setUseWideViewPort(true);//设置缩放密度
        webSetting.setSupportMultipleWindows(false);//设置WebView是否支持多窗口,如果为true需要实现onCreateWindow(WebView, boolean, boolean, Message)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //两者都可以
            webSetting.setMixedContentMode(webSetting.getMixedContentMode());//设置安全的来源
        }
        webSetting.setAppCacheEnabled(true);//设置应用缓存
        webSetting.setDomStorageEnabled(true);//DOM存储API是否可用
        webSetting.setGeolocationEnabled(true);//定位是否可用
        webSetting.setLoadWithOverviewMode(true);//是否允许WebView度超出以概览的方式载入页面，
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);//设置应用缓存内容的最大值
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);//设置是否支持插件
        webSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);//重写使用缓存的方式
        webSetting.setAllowUniversalAccessFromFileURLs(true);//是否允许运行在一个file schema URL环境下的JavaScript访问来自其他任何来源的内容
        webSetting.setAllowFileAccessFromFileURLs(true);//是否允许运行在一个URL环境

        wv_content.setHorizontalScrollBarEnabled(false);//水平不显示
        wv_content.setVerticalScrollBarEnabled(false); //垂直不显示


    }


    public static void handlerViewClickTime(View v) {
        final long[] mHits = new long[2];
        System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
        mHits[mHits.length - 1] = SystemClock.uptimeMillis();
        if (mHits[0] < (SystemClock.uptimeMillis() - 300)) {
            v.performClick();
        } else {
            Logger.d("重复点击");
        }
    }


    public static String handlePhone(String phone) {
        if (TextUtils.isEmpty(phone)) return "";
        String starString = "****";

        return phone.substring(0, 6) + starString + phone.substring(phone.length() - 4, phone.length());
    }


    /**
     * 格式化字符串，每三位用逗号隔开
     *
     * @param str
     * @return
     */
    public static String addComma(String str) {
        str = new StringBuilder(str).reverse().toString();     //先将字符串颠倒顺序
        if (str.equals("0")) {
            return str;
        }
        StringBuilder str2 = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            if (i * 3 + 3 > str.length()) {
                str2.append(str.substring(i * 3, str.length()));
                break;
            }
            str2.append(str.substring(i * 3, i * 3 + 3)).append(",");
        }
        if (str2.toString().endsWith(",")) {
            str2 = new StringBuilder(str2.substring(0, str2.length() - 1));
        }
        //最后再将顺序反转过来
        String temp = new StringBuilder(str2.toString()).reverse().toString();
        //将最后的,去掉
        return temp.substring(0);
    }


    public static void setHintTextSize(EditText editText, String hintText, int textSize) {
        SpannableString ss = new SpannableString(hintText);
        // 新建一个属性对象,设置文字的大小
        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(textSize, true);
        // 附加属性到文本
        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        // 设置hint
        editText.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失
    }


    public static String getDoublePercent(double text) {
        return String.format("%.2f", text * 100d);
    }


    public static String[] ENGLISH_NUMBER = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"};

    @Nullable
    public static String getNumberToEnglish(int limitNum) {
        if (limitNum > ENGLISH_NUMBER.length) return "";
        return ENGLISH_NUMBER[limitNum];
    }

    public static void setTextMessageCount(TextView tvCount, int count) {
        if (count > 0) {
            if (count > 99) {
                tvCount.setText("99+");
                tvCount.setTextSize(8f);
            } else {
                tvCount.setText(String.valueOf(count));
            }
            tvCount.setVisibility(View.VISIBLE);

        } else {
            tvCount.setVisibility(View.GONE);
        }

    }

    public static void initActivityTimeCountdown(long timeDifferLong, TextView tvDay, TextView tvHour, TextView tvMinute, TextView tvSecond, TimeCountdownListener listener) {
        //  endTime="2019-10-10T11:25:59.999000Z";

        if (timeDifferLong <= 0) {
            listener.onComplete();
            return;
        }

        setTimeView(timeDifferLong, tvDay, tvHour, tvMinute, tvSecond);
        startTimeCountdown(timeDifferLong, tvDay, tvHour, tvMinute, tvSecond, listener);
    }

    private static void setTimeView(long timeDifferLong, TextView tvDay, TextView tvHour, TextView tvMinute, TextView tvSecond) {
        long day = TimeUtils.dateDiffDay(timeDifferLong);
        tvDay.setText(day + "");
        long hour = TimeUtils.dateDiffHour(timeDifferLong);
        tvHour.setText(String.format("%02d", hour));

        long minute = TimeUtils.dateDiffMinute(timeDifferLong);
        tvMinute.setText(String.format("%02d", minute));
        long second = TimeUtils.dateDiffSecond(timeDifferLong);
        tvSecond.setText(String.format("%02d", second));
    }

    private static void startTimeCountdown(final long timeDifferLong, final TextView tvDay, final TextView tvHour, final TextView tvMinute, final TextView tvSecond, final TimeCountdownListener timeCountdownListener) {

        Observable.interval(0, 1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.newThread())

                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(Long increaseTime) throws Exception {
                        return timeDifferLong - increaseTime.intValue();
                    }
                }).take(timeDifferLong + 1, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new CommonObserver<Long>() {
            @Override
            public void onSubscribe(Disposable d) {
                super.onSubscribe(d);
                if (timeCountdownListener != null) timeCountdownListener.onStart(d);
            }

            @Override
            public void onNext(Long aLong) {
                super.onNext(aLong);
                if (aLong > 0) {
                    setTimeView(aLong, tvDay, tvHour, tvMinute, tvSecond);
                    if (timeCountdownListener != null) timeCountdownListener.onNext(aLong);
                }
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                if (timeCountdownListener != null) timeCountdownListener.onError();
            }

            @Override
            public void onComplete() {
                super.onComplete();

                if (timeCountdownListener != null) timeCountdownListener.onComplete();
            }
        });


    }

    public static void handleHomeSquareSpannable(String content, String handleContent, TextView tvContent) {
        SpannableStringBuilder builder = new SpannableStringBuilder(content);
        ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(UIUtils.getColor(R.color.gray_4c));
        builder.setSpan(foregroundColorSpan, 0, handleContent.length() + 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        builder.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, handleContent.length() + 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        tvContent.setText(builder);
    }

    public static SpannableStringBuilder getSquareSpannable(String content, String handleContent, TextView tvContent) {
        SpannableStringBuilder builder = new SpannableStringBuilder(content);
        ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(UIUtils.getColor(R.color.gray_4c));
        builder.setSpan(foregroundColorSpan, 0, handleContent.length() + 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        builder.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, handleContent.length() + 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        return builder;
    }

    public static String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            StringBuilder result = new StringBuilder();
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result.append(temp);
            }
            return result.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static int getRegExpTextLength(String validateStr) {
        // String temp = validateStr.replaceAll("[\u4e00-\u9fa5]", "**");
        String temp = validateStr.replaceAll("[^\\x00-\\xff]", "**");
        return temp.length();
    }

    public static void clearFragmentCache(FragmentActivity activity, FragmentPagerAdapter fragmentAdapter) {
        clearFragmentCache(activity.getSupportFragmentManager(), fragmentAdapter);

    }

    public static void clearFragmentCache(FragmentManager mFragmentManager, FragmentPagerAdapter fragmentAdapter) {
        if (fragmentAdapter == null) return;
        try {
            int size = fragmentAdapter.getCount();
            FragmentTransaction mCurTransaction = mFragmentManager.beginTransaction();
            for (int i = 0; i < size; i++) {
                Fragment fragment = fragmentAdapter.getItem(i);
                //if (fragment.isAdded()) {
                    mCurTransaction.remove(fragment);
               // }
            }
            mCurTransaction.commitNowAllowingStateLoss();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String htmlFormat(String html) {
        return html;
       /* StringBuffer sb = new StringBuffer();
        return sb.append("<html>")
                .append("<head>")
                .append("<meta http-equiv='Content-Type' content='text/html'; charset='UTF-8'>")
                .append("<style type='text/css'>")
                .append("#box {display: flex;justify-content: center;}")
                .append("</style>")
                .append("<title>")
                .append("</title>")
                .append("</head>")
                .append("<body style='text-align: center;'>")
                .append("<div id='box'>")
                .append(html)
                .append("</div>")
                .append("</body>")
                .append("</html>").toString();*/
    }

    public static void copyText(String text) {
        ClipboardManager cmb = (ClipboardManager) UIUtils.getContext().getSystemService(CLIPBOARD_SERVICE);
        cmb.setText(text);
        ToastUtils.showShort("复制成功  " + text);
    }

    /**
     * 获取屏幕高度
     */
    public static int getScreenHeight(Context context) {
        DisplayMetrics dm = context.getApplicationContext()
                .getResources().getDisplayMetrics();
        return dm.heightPixels;
    }
    /**
     * 获取获取系统状态栏高度。
     *
     * @param appContext APP的上下文
     * @return 状态栏高度
     */
    public static int getStatusBarHeight(Context appContext) {
        int result = 0;
        int resourceId = appContext.getResources().getIdentifier
                ("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = appContext.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /** dp转化成px */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getApplicationContext().getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /** sp转换成px */
    public static int sp2px(Context context, float spValue) {
        float fontScale=context.getApplicationContext().getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue*fontScale+0.5f);
    }
}
